package com.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.*;

@RestController
@Api(tags = "downloadFile")
public class DownloadController {

    @ApiOperation(value = "本地文件下载到前端")
    @PostMapping("/download")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "fileName", value = "文件名", required = true, dataType = "String")
    })
    public void downloadLocal(String fileName, HttpServletResponse response) throws IOException{
        OutputStream outputStream=null;
        InputStream inputStream=null;
        BufferedInputStream bufferedInputStream=null;
        byte[] bytes=new byte[1024];
        String path = "D:/24926/Desktop/MyProject/FILES/files/" + fileName;
        File file = new File(path);

        if (! file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
//            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("文件不存在，请检查文件名是否正确");
            return;
        }

        try {response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 以流的形式返回文件
            response.setContentType("application/octet-stream");
            inputStream = Files.newInputStream(file.toPath());
            bufferedInputStream = new BufferedInputStream(inputStream);
            outputStream = response.getOutputStream();
            int i = bufferedInputStream.read(bytes);
            while (i != -1) {
                outputStream.write(bytes, 0, i);
                i = bufferedInputStream.read(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
